#!/usr/bin/env python3
"""
待办事项路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db, Todo

bp = Blueprint('todos', __name__)

@bp.route('/', methods=['GET'])
@jwt_required()
def get_todos():
    """获取待办事项，支持分页/筛选/排序
    查询参数：
      - page: 页码（默认1）
      - per_page: 每页数量（默认20）
      - q: 文本搜索（模糊匹配 text）
      - completed: 过滤完成状态（true/false，可选）
      - sort: 排序字段（created_at|-created_at，默认 -created_at）
    """
    try:
        current_user_id = int(get_jwt_identity())

        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        q = request.args.get('q', type=str)
        completed_param = request.args.get('completed', type=str)
        sort = request.args.get('sort', '-created_at')

        query = Todo.query.filter_by(user_id=current_user_id)

        if q:
            query = query.filter(Todo.text.like(f"%{q}%"))

        if completed_param is not None:
            if completed_param.lower() in ('true', '1', 'yes'):
                query = query.filter(Todo.completed.is_(True))
            elif completed_param.lower() in ('false', '0', 'no'):
                query = query.filter(Todo.completed.is_(False))

        if sort == 'created_at':
            query = query.order_by(Todo.created_at.asc())
        else:
            query = query.order_by(Todo.created_at.desc())

        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        items = [todo.to_dict() for todo in pagination.items]

        return jsonify({
            'todos': items,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/', methods=['POST'])
@jwt_required()
def create_todo():
    """创建新待办事项"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('text'):
            return jsonify({'error': '待办事项内容不能为空'}), 400
        
        todo = Todo(
            user_id=current_user_id,
            text=data['text'],
            completed=data.get('completed', False)
        )
        
        db.session.add(todo)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'todo': todo.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/<int:todo_id>', methods=['PUT'])
@jwt_required()
def update_todo(todo_id):
    """更新待办事项"""
    try:
        current_user_id = int(get_jwt_identity())
        todo = Todo.query.filter_by(id=todo_id, user_id=current_user_id).first()
        
        if not todo:
            return jsonify({'error': '待办事项不存在'}), 404
        
        data = request.get_json()
        
        if 'text' in data:
            todo.text = data['text']
        if 'completed' in data:
            todo.completed = data['completed']
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'todo': todo.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/<int:todo_id>', methods=['DELETE'])
@jwt_required()
def delete_todo(todo_id):
    """删除待办事项"""
    try:
        current_user_id = int(get_jwt_identity())
        todo = Todo.query.filter_by(id=todo_id, user_id=current_user_id).first()
        
        if not todo:
            return jsonify({'error': '待办事项不存在'}), 404
        
        db.session.delete(todo)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '待办事项已删除'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

